<?php

namespace app\api\controller;

use app\api\model\AuthGroup;
use app\api\model\AuthMenu;
use app\api\model\Manager;
use app\common\logic\Auth;
use think\facade\Validate;
use app\common\logic\Data;
use app\lib\exception\ApiException;
use app\lib\Result;

class User extends Base
{
  public function info()
  {
    $user    = $this->user;
    $user['role'] = $this->getrole(0);
    return json(['code' => 200, 'data' => $user, 'msg' => '获取成功']);
  }
  public function getrole($outFun = 1)
  {
    if ($this->user['is_admin'] === 1) {
      $where = ['status' => 1];
    } else {
      $getRulesInfo = getAuthGroupById($this->user['groupId'], $this->user['manager_id']);
      $getRulesInfo['rules'] = $getRulesInfo['rules'] . ',' . $getRulesInfo['halfrules'];
      $getRules['name'] = $getRulesInfo['title'];
      $getRules['describe'] = $getRulesInfo['desc'];
      $rulesArr = explode(',', $getRulesInfo['rules']);
      $where = ['id' => ['in', $rulesArr], 'status' => 1];
    }
    $rulesList = AuthMenu::where($where)->order('sort', ' asc')->select()->toArray();
    $access = (new Data)->listToTreeMulti($rulesList, 0, 'id', 'pid', 'children');
    $routers = [];
    $permissionList = [];
    foreach ($access as $v) {
      foreach ($v['children'] as $vo) {
        $actArr = [];
        $act2Arr = [];
        $per['roleId'] = $this->user['groupId'];
        $per['permissionId'] = $vo['key'];
        $per['permissionName'] = $vo['title'];
        foreach ($vo['children'] as $vo2) {
          if (isset($vo2['children']) && !empty($vo2['children'])) {
            foreach ($vo2['children'] as $vo3) {
              $act2 = $act['action'] = $vo3['key'];
              $act['describe'] = $vo3['title'];
              $act['defaultCheck'] = true;
              array_push($actArr, $act);
              array_push($act2Arr, $act2);
            }
          }
          $act2 = $act['action'] = $vo2['key'];
          $act['describe'] = $vo2['title'];
          $act['defaultCheck'] = true;
          array_push($actArr, $act);
          array_push($act2Arr, $act2);
        }
        $per['actions'] = json_encode($actArr);
        $per['actionEntitySet'] = $actArr;
        $per['actionList'] = $act2Arr;
        $per['dataAccess'] = null;
        array_push($routers, $per);
        array_push($permissionList, $vo['key']);
      }
    }
    $getRules['permissions'] = $routers;
    $getRules['permissionList'] = $permissionList;
    if ($outFun == 1) {
      return json(['code' => 200, 'data' => $getRules, 'msg' => '获取成功']);
    } else {
      return $getRules;
    }
  }
  public function getmenu()
  {
    if ($this->user['is_admin'] == 1) {
      $where['status'] = 1;
      $where['type'] = ['1', '2'];
    } else {
      $ruleString = Auth::getRuleId($this->user['groupId']);
      $rulesArr = explode(',', $ruleString);
      $where = ['id' => $rulesArr, 'status' => 1, 'type' => [1, 2]];
    }
    $rulesList = AuthMenu::where($where)->order('sort', 'asc')->select()->toArray();
    foreach ($rulesList as &$vo) {
      if (empty($vo['filePath'])) {
        $vo['filePath'] = $vo['key'];
      }
      $vo['hideChildrenInMenu'] = ($vo['hideChildrenInMenu'] == 1) ? true : false;
      $vo['hidden'] = ($vo['hidden'] == 1) ? true : false;
      $vo['icon'] = 'anticon-' . $vo['icon'];
    }
    return json(['code' => 200, 'data' => $rulesList, 'msg' => '获取成功']);
  }
  private static function getMenuTree($data)
  {
    $treeData = array();
    foreach ($data as $vo) {
      if (isset($vo['children'])) {
        $vo1['key'] = $vo['key'];
        $vo1['filePath'] = $vo['filePath'];
        $vo1['icon'] = $vo['icon'];
        $vo1['component'] = $vo['component'];
        $vo1['title'] = $vo['title'];
        $vo1['hideChildrenInMenu'] = $vo['hideChildrenInMenu'];
        $vo1['hidden'] = $vo['hidden'];
        $vo1['children'] = self::getMenuTree($vo['children']);
        $treeData[] = $vo1;
      }
    }
    return $treeData;
  }
  /**
   * 获取管理员列表
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function getUserList()
  {
    $rule = [
      'pageNo'  => 'number',
      'title'  => 'chsDash',
      'type'  => 'number',
      'pageSize'  => 'number',
    ];
    $data = [
      'pageNo' => input('param.pageNo', 1, 'trim'),
      'title' => input('param.title', '', 'trim'),
      'type' => input('param.type', '0', 'trim'),
      'pageSize' => input('param.pageSize', 10, 'trim'),
    ];
    $validate = Validate::rule($rule);
    $result   = $validate->check($data);
    if (!$result) {
      return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
    }
    $where['manager_id'] = $this->user['manager_id'];
    if ($data['type'] == 1) {
      $where['status'] = 1;
    } elseif ($data['type'] == -1) {
      $where['status'] = -1;
    }
    if (!empty($data['title'])) {
      $where['phone'] = ['like', '%' . $data['title'] . '%'];
    }
    $limit = ($data['pageNo'] - 1) * $data['pageSize'];
    $dataList = Manager::field('id,phone,create_time,login_time,status,login_ip,groupId,realName,avatar,is_admin,username')->where($where)->order('id', 'asc')->limit($limit, $data['pageSize'])->select()->toArray();
    $authGroupList = getAuthGroupListByMid($this->user['manager_id']);
    $authList = [];
    foreach ($authGroupList as $key => $vo) {
      $authArr[$vo['id']] = $vo['title'];
      $info['id'] = (string) $vo['id'];
      $info['title'] = $vo['title'];
      $info['disabled'] = ($vo['status'] == 1) ? false : true;
      $authList[] = $info;
    }
    foreach ($dataList as &$vo) {
      $vo['phone'] = dataTuomin($vo['phone'], 3, 4);
      $vo['login_time'] = date('Y-m-d H:i:s', $vo['login_time']);
      $vo['create_time'] = date('Y-m-d H:i:s', $vo['create_time']);
      $vo['avatar'] = (!empty($vo['avatar'])) ? $vo['avatar'] : config('app.SYS_STATIC.defaultAvatar');
      if ($this->uid == $vo['id']) {
        $vo['self'] = 1;
      } else {
        $vo['self'] = 0;
      }
      if (!empty($vo['groupId'])) {
        $vo['groupId'] = explode(',', $vo['groupId']);
        foreach ($vo['groupId'] as $voId) {
          $vo['groupName'][] = (isset($authArr[$voId])) ? $authArr[$voId] : '未知';
        }
        $vo['groupName'] = implode('|', $vo['groupName']);
      } else {
        $vo['groupName'] = '无';
        $vo['groupId'] = [];
      }
    }
    $returnData['data']['data'] = $dataList;
    $returnData['data']['authList'] = $authList;
    $returnData['data']['totalCount'] = Manager::where($where)->count('id');
    $returnData['code'] = 200;
    $returnData['msg'] = '获取成功';
    return json($returnData);
  }
  /**
   * 编辑/添加用户信息
   * @Author Qianlong <87498106@qq.com>
   * @PersonSite http://dev.21ds.cn/
   */
  public function editUserInfo()
  {
    if (request()->isPost()) {
      $rule = [
        'id'  => 'number',
        'password|密码'  => 'alphaDash|min:8|max:26',
        'avatar|头像'  => 'min:12|max:120',
        'realName|真实姓名'  => 'chsDash',
        'groupId|角色组'  => 'alphaDash',
        'status|状态'  => 'require|number',
        'username|用户名'  => 'require',
        'phone|手机号'  => 'require|mobile',
      ];
      $data = [
        'id' => input('param.id', '', 'trim'),
        'username' => input('param.username', '', 'trim'),
        'phone' => input('param.phone', '', 'trim'),
        'password' => input('param.password', '', 'trim'),
        'avatar' => input('param.avatar', '', 'trim'),
        'realName' => input('param.realName', '', 'trim'),
        'groupId' => input('param.groupIds', '', 'trim'),
        'status' => input('param.status', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      /**
       * 同账户同名唯一性判断
       */
      if (!empty($data['username'])) {
        unset($data['force']);
        $whereUnique['username'] = $data['username'];
        $uniqueTitle = Manager::field('id')->where($whereUnique)->find();
        if (!empty($uniqueTitle) && $uniqueTitle['id'] != $data['id']) {
          return json(['code' => -2, 'data' => '', 'msg' => $data['username'] . ' 已存在，不允许添加']);
        }
      }
      if (empty($data['id'])) {
        $manage['phone'] = $data['phone'];
        $manage['salt'] = make_salt();
        $manage['password'] = md5($data['password'] . $manage['salt']);
        $manage['create_time'] = $this->time;
        $manage['status'] = $data['status'];
        $manage['is_admin'] = 0;
        $manage['groupId'] = (is_array($data['groupId'])) ? implode(',', $data['groupId']) : $data['groupId'];
        $manage['manager_id'] = $this->p_mid;
        $manage['username'] = $data['username'];
        $manage['avatar'] = $data['avatar'];
        $manage['realName'] = $data['realName'];
        Manager::insert($manage);
        return json(['code' => 200, 'data' => '', 'msg' => '添加成功']);
      } else {
        $whereHas['id'] = $data['id'];
        $whereHas['manager_id'] = $this->p_mid;
        $hasTitle = Manager::field('avatar')->where($whereHas)->find();
        if (empty($hasTitle)) {
          return json(['code' => -1, 'data' => '', 'msg' => '非法编辑，请刷新后重试']);
        }
        $cacheData['id'] = $data['id'];
        $this->delRedisCache($cacheData);
        if (!empty($data['password'])) {
          $manage['salt'] = make_salt(7);
          $manage['password'] = md5($data['password'] . $manage['salt']);
        }
        if (empty($data['avatar'])) {
          unset($data['avatar']);
        } else {
          $manage['avatar'] = $data['avatar'];
          if ($hasTitle['avatar'] != $data['avatar']) {
            // deleteOssFile($hasTitle['avatar']);
          }
        }
        if (!empty($data['phone']) && strpos($data['phone'], '**') !== false) {
          $manage['phone'] = $data['phone'];
        }
        $manage['status'] = $data['status'];
        if (!empty($data['realName'])) {
          $manage['realName'] = $data['realName'];
        }
        if (!empty($data['groupId'])) {
          $manage['groupId'] = (is_array($data['groupId'])) ? implode(',', $data['groupId']) : $data['groupId'];
        }
        $status = Manager::where('id', $data['id'])->update($manage);
        if ($status > 0) {
          return json(['code' => 200, 'data' => '', 'msg' => '修改成功']);
        } else {
          return json(['code' => -1, 'data' => '', 'msg' => '修改失败，请重试']);
        }
      }
    }
  }
  public function delUser()
  {
    if (request()->isPost()) {
      $rule = [
        'id'  => 'number',
      ];
      $data = [
        'id' => input('param.id', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return json(['code' => -1, 'data' => '', 'msg' => $validate->getError()]);
      }
      $status = Manager::where('id', $data['id'])->where('manager_id', $this->p_mid)->delete();
      if ($status > 0) {
        return json(['code' => 200, 'data' => '', 'msg' => '删除成功']);
      } else {
        return json(['code' => -1, 'data' => '', 'msg' => '删除失败，请重试']);
      }
    }
  }
  public function getAuthGroup()
  {
    $dataList = AuthGroup::field('id,status,title')->where('mid', $this->p_mid)->order('id', 'asc')->select()->toArray();
    foreach ($dataList as &$vo) {
      $vo['disabled'] = ($vo['status'] == 1) ? false : true;
      $vo['id'] = (string) $vo['id'];
      unset($vo['status']);
    }
    return json(['code' => 200, 'data' => $dataList, 'msg' => '获取成功']);
  }
  public function refresh_token()
  {
    $hasUser = Manager::field('is_admin,groupId,username,avatar')->where('id', $this->uid)->find();
    $rules = Auth::getRuleId($hasUser['groupId']);
    $tokenArr['rules'] = Auth::getRuleKey($rules);
    $tokenArr['userToken'] = $this->redis->get('token-' . $this->uid);
    //用户登录有效期
    $loginExpireTime = config('app.SYS_STATIC.login_expire');
    // 存储用户token
    $tokenArr['Expire'] = $loginExpireTime * 1000;
    $tokenArr['loginExpire'] = ($loginExpireTime + time())*1000;
    $tokenArr['isSuper'] = $hasUser['is_admin'];
    $tokenArr['username'] = $hasUser['username'];
    $tokenArr['avatar'] = $hasUser['avatar'];
    return Result::Success($tokenArr);
  }
  // 删除redis缓存
  private function delRedisCache($data = [])
  {
    delRedisCache('getmanager_list_by_prid-' . $this->p_mid);
    if (isset($data['id'])) {
      delRedisCache('getAuthApiListById-' . $this->user['id']);
      delRedisCache('getmanager_by_id-' . $this->p_mid . '-' . $data['id']);
    }
    delRedisCache('getManagerPage1ListByMid-' . $this->p_mid);
  }
}
